<?php

namespace app\middleware;

use app\proxy\MyRequest;
use app\Request;
use app\service\RedisService;
use app\utils\Utils;
use think\facade\Cache;
use think\facade\Log;
use think\helper\Str;

class TokenMiddleware
{
    var $whiteList = [
        "/auth\/login/",
        "/phpinfo/",
        "/file\/uploadone/",
        "/storage/",
          "/public/",
        "/static/"
    ];

    /*
     * 判断用户是否有token 有登陆过
     * 排除白名单
     * */
    public function handle( $request, \Closure $next){
        $currentUrl = $request->baseUrl();
        Log::info("操作路径 $currentUrl");
        $filterList = array_filter($this->whiteList, function ($str) use ($currentUrl) {
            return preg_match("$str","$currentUrl");
        });
//        dd($filterList,count($filterList));
        $isyes = count($filterList) > 0;
        if ($isyes) {
            return $next($request);
        }

        $authorizationstr=$request->header('Authorization');
        $token = substr($authorizationstr,7,strlen($authorizationstr));
//        dd($token,is_null($token));
        /* 判断 token 是否可以在 redis找到 */
        if (is_null($token)) {
            return json(['code' => 401, 'message' => '没有token'], 401);
        }
        /*redis 能不能找到东西*/
//        $userFromRedis = Cache::store("redis")->get("token:$token");
        $userFromRedis = RedisService::$client->get("token:$token");
        // Log::info("user  json from redis==>",);
        if (is_null($userFromRedis)) {
            return json(['code' => 401, 'message' => 'token失效'], 401);
        }
        $userFromRedis = json_decode($userFromRedis, true);
        $request->setUserInfo($userFromRedis);
//        $request->setUserInfo=($userFromRedis);
        return $next($request);
    }

}